#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/param.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<time.h>

int main(){
    //system("mkdir /tcrwork");
    //system("mkdir /tcrwork/hmiMain");
    //system("mkdir /tcrwork/lib");

    system("chmod 777 /etc/init.d/rcS");
    system("chmod 777 /tcrwork");
    system("chmod 777 /tcrwork/hmiMain");
    system("chmod 777 /tcrwork/lib");

	system("echo '0'>/tcrwork/forkflag.data");

	FILE *fp;
	char tmp[10] = {0};

	while(1)
	{
		fp=fopen("/tcrwork/forkflag.data","r");
		if(fread(tmp, 1, 1, fp) == 1)
        {

			fclose(fp);
            fp = NULL;

			if(tmp[0] == '0')
            {
				system("for var in /tcrwork/lib/*so.1.0.0;do mv $var ${var%so.1.0.0}so.1;done");

				system("mv /tcrwork/hmiMain/hmiMain /tcrwork/hmiMain/hmi");

				system("/tcrwork/hmiMain/hmi -qws&");

                system("echo '1'>/tcrwork/forkflag.data");
			}
            else if(tmp[0] == '1')
            {
				sleep(1);
                //正常开启ing
				//break;//暂时break
            }
            else if(tmp[0] == '2')//调用校准
            {
                system("killall hmi");
                system("echo 1-killall hmi $?");

                system("rm /etc/pointercal");
                system("echo rm /etc/pointercal $?");

                system("sleep 0.1");
                system("echo sleep 0.1 $?");

                system("/opt/tslib/bin/ts_calibrate");
                system("echo /opt/tslib/bin/ts_calibrate $?");

                system("killall ts_calibrate");
                system("echo killall ts_calibrate $?");

                system("echo '0'>/tcrwork/forkflag.data");//重启
            }
            else if(tmp[0] == '3')//重启系统
            {
                system("killall  hmi");

                system("sleep 0.1");

				system("echo '0'>/tcrwork/forkflag.data");//重启

                system("reboot");
            }

		}
		else
		{
			fclose(fp);
            fp = NULL;

			system("for var in /tcrwork/lib/*so.1.0.0;do mv $var ${var%so.1.0.0}so.1;done");

			system("mv /tcrwork/hmiMain/hmiMain /tcrwork/hmiMain/hmi");

			system("/tcrwork/hmiMain/hmi -qws&");

            system("echo '1'>/tcrwork/forkflag.data");
		}
	}

    return 0;
}
